/**
 *
 */
package net.hvacapp.cmvrfforandroid.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXTextObject;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import net.hvacapp.cmvrfforandroid.AppManager;
import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.constant.Constant;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author hailong.han
 * @description 2014年8月27日
 * 
 */
public class UIHelper {
    /**
     * 发送App异常崩溃报告
     *
     * @param cont
     * @param crashReport
     */
    public static void sendAppCrashReport(final Context cont,
                                          final String crashReport) {
        AlertDialog.Builder builder = new AlertDialog.Builder(cont);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setTitle(R.string.app_error);
        builder.setMessage(R.string.app_error_message);
        builder.setPositiveButton(R.string.submit_report,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 发送异常报告
                        Intent i = new Intent(Intent.ACTION_SEND);
                        i.setType("message/rfc822"); // 真机
                        i.putExtra(Intent.EXTRA_EMAIL,
                                new String[]{"hailong.han@cubead.com"});
                        i.putExtra(Intent.EXTRA_SUBJECT,
                                cont.getString(R.string.app_error_text_report));
                        i.putExtra(Intent.EXTRA_TEXT, crashReport);
                        cont.startActivity(Intent.createChooser(i, cont
                                .getString(R.string.app_error_text_report_send)));
                        // 退出
                        AppManager.getAppManager().AppExit();
                    }
                });
        builder.setNegativeButton(R.string.confirm,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 退出
                        AppManager.getAppManager().AppExit();
                    }
                });
        builder.show();
    }

    /**
     * 拦截处理带有业务意义的ErrorCode
     * @param json
     */
    public static void handleErrorCode(String json) {
        if (TextUtils.isEmpty(json)) {
            return;
        }

    }


    public static void shareFunctionWithUI(final Activity context, final String title, final String content, final String tagetUrl, final Bitmap data) {

        BitmapFactory.Options option = new BitmapFactory.Options();
        option.inSampleSize = 1;
        option.inJustDecodeBounds = false;
        Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.app_share_icon, option);

        final Bitmap bmp = ThumbnailUtils.extractThumbnail(bm, 120, 120); //将图片的大小限定在100*100
        final String[] items = context.getResources().getStringArray(
                R.array.share_item);
        new AlertDialog.Builder(context)
                .setTitle("分享到")
                .setItems(items, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog,
                                        int which) {
                        if (which == 0) {
                            //微信
                            shareToWX(context, title, tagetUrl, content, bmp);
                        }
                        else {
                            //朋友圈
                            shareToWXCircle(context, title, tagetUrl, content, bmp);
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }

    /**
     * 创建进度条对话框
     *
     * @param context
     * @param tip
     * @return
     */
    public static Dialog createProgressBarDialog(Context context, String tip) {

        final Dialog dialog = new Dialog(context, R.style.dialog);
        dialog.setContentView(R.layout.progressbar_dialog);
        dialog.setCanceledOnTouchOutside(false);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        int width = WindowUtils.getScreenWidth(context);
        lp.width = (int) (0.6 * width);

        TextView titleTxtv = (TextView) dialog.findViewById(R.id.tvLoad);

        titleTxtv.setText(tip);
        return dialog;
    }


    /**
     * 分享到微信
     *
     * @param context
     *            上下文
     * @param title
     *            标题
     * @param url
     *            链接
     * @param shareContent
     *            内容
     */
    public static void shareToWX(final Activity context, String title,
                                 String url, String shareContent, Bitmap image) {
        IWXAPI api;
        api = WXAPIFactory.createWXAPI(context, Constant.APP_ID, true);
        api.registerApp(Constant.APP_ID);

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);

        msg.title =title;
        msg.description = shareContent;
        msg.setThumbImage(image);
//        msg.thumbData = compressBitmap(image, 30*1000);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("wxcircle");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);

    }

    /**
     * 分享到微信朋友圈
     *
     * @param context
     *            上下文
     * @param title
     *            标题
     * @param url
     *            链接
     * @param shareContent
     *            内容
     */
    public static void shareToWXCircle(final Activity context, String title,
                                       String url, String shareContent, Bitmap bmp) {
        IWXAPI api;
        api = WXAPIFactory.createWXAPI(context, Constant.APP_ID, true);
        api.registerApp(Constant.APP_ID);

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);

        msg.title =title;
        msg.description = shareContent;
        msg.setThumbImage(bmp);
//        msg.thumbData = compressBitmap(bmp, 30*1000);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("wxcircle");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneTimeline;
        api.sendReq(req);
    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    /**
     * 基于质量的压缩算法， 此方法未 解决压缩后图像失真问题
     * <br> 可先调用比例压缩适当压缩图片后，再调用此方法可解决上述问题
     * @param bitmap
     * @param maxBytes 压缩后的图像最大大小 单位为byte
     * @return
     */
    public static byte[] compressBitmap(Bitmap bitmap, long maxBytes) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            int options = 90;
            while (baos.toByteArray().length > maxBytes) {
                baos.reset();
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
                options -= 10;
            }
            byte[] bts = baos.toByteArray();
//            Bitmap bmp = BitmapFactory.decodeByteArray(bts, 0, bts.length);
            baos.close();
            return bts;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);

        return m.matches();
    }

    public static boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;

        String expression = "((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches() ) {
            isValid = true;
        }
        return isValid;
    }
}
